﻿using System;
using System.IO;
using System.Text;

using System.Runtime.Serialization;

namespace SBPweb.Communication.Client.Library.Serialization
{

    public class ObjectSerializer
    {

        public static string Serialize(object obj)
        {
            if (obj == null)
            {
                return null;
            }
            if (obj is string)
            {
                return obj.ToString();
            }

            Type type = obj.GetType();
            DataContractSerializer dS = new DataContractSerializer(type);
            MemoryStream stream = new MemoryStream();
            dS.WriteObject(stream, obj);
            stream.Flush();

            byte[] bytes = stream.ToArray();
            string ret = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
            return ret;
        }

        public static object Deserialize(string fragment, Type possibleType)
        {
            if (fragment == null)
            {
                return null;
            }
            DataContractSerializer dS = new DataContractSerializer(possibleType);
            MemoryStream stream = new MemoryStream();
            byte[] bytes = Encoding.UTF8.GetBytes(fragment);
            stream.Write(bytes, 0, bytes.Length);
            stream.Flush();
            stream.Seek(0, SeekOrigin.Begin);
            object o = dS.ReadObject(stream);
            return o;
        }

    }

}